package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Dish;
import com.itheima.reggie.service.DishService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;

/**
 * @Author fanYuLe
 * @Date 2023/3/5 10:59
 * @Blog blog.fanYuLe.net/996.mba
 * @Description:
 */
@RestController
public class DishController {
    @Autowired
    private DishService dishService;
    @Autowired
    private RedisTemplate redisTemplate;
    //菜品列表分页查询
    @GetMapping("/dish/page")
    public ResultInfo findByPage(@RequestParam(value = "page",defaultValue = "1") Integer pageNum,
                                 @RequestParam(value = "pageSize",defaultValue = "10") Integer pageSize,
                                 String name){
        Page<Dish> dishPage =dishService.findByPage(pageNum,pageSize,name);
        return ResultInfo.success(dishPage);
    }
    //新增菜品
    @PostMapping("/dish")
    public ResultInfo save(@RequestBody Dish dish){
        dishService.save(dish);
        //清理缓存
        String dishKey= "dish_"+dish.getCategoryId();
        redisTemplate.delete(dishKey);
        return ResultInfo.success();
    }
    //抽取删除公共方法
    private void clean(String key) {
        Set keys = redisTemplate.keys(key);
        redisTemplate.delete(keys);
    }

    //菜品修改
    //回显菜品
    @GetMapping("/dish/{dishId}")
    public ResultInfo findById(@PathVariable("dishId") Long dishId){
       return ResultInfo.success(dishService.findById(dishId));
    }
    //修改菜品信息
    @PutMapping("/dish")
    public ResultInfo updateDish(@RequestBody Dish dish){
        dishService.updateDish(dish);
        //清理缓存
        clean("dish_*");
        return ResultInfo.success();
    }



    //菜品起售，停售
    @PostMapping("/dish/status/{status}")
    public ResultInfo updateStatus(@PathVariable("status") Integer status,
                                   @RequestParam List<Long> ids){
        dishService.updateStatus(status,ids);
        //清理缓存
        clean("dish_*");
        return ResultInfo.success();
    }
    //菜品删除
    @DeleteMapping("/dish")
    public ResultInfo deleteDish(@RequestParam List<Long> ids){
        dishService.deleteDish(ids);
        //清理缓存
        clean("dish_*");
        return ResultInfo.success();
    }

    //回显菜品列表
    //前台发送请求，根据categoryId查询分类下的菜品列表
    @GetMapping("/dish/list")
    public ResultInfo findBycategoryId(Long categoryId,String name){
        List<Dish> dishList=dishService.findBycategoryId(categoryId,name);
        return ResultInfo.success(dishList);
    }
}

